package edu.hrbu.spring.service.impl;

import edu.hrbu.spring.dao.AccountDao;
import edu.hrbu.spring.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 徐登宇
 */
@Transactional // 开启声明式事务（注解 在该类所有方法上开启）
@Service
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDaoImpl")
    AccountDao accountDao;

    @Override
    public boolean transfer(int fromId, int toId, int balance) {
        int i = 0; // 转账是否成功的标记【2：成功】
        // 转款人的账户余额
        int fromBalance = accountDao.selectById(fromId);
        // 收款人的账户余额
        int toBalance = accountDao.selectById(toId);
        if (fromBalance < balance || fromBalance <= 0) { // 转账余额不足
            System.err.println("【转账失败】余额不足");
        }

        i += accountDao.update(fromId, fromBalance - balance); // 转款

        int n = 1/0; // 模拟异常

        i += accountDao.update(toId, toBalance + balance); // 收款
        return i == 2;
    }
}
